package com.shadowtorcher.stdisk.logic;

import com.shadowtorcher.soulknife.SoulKnifeDB;
import com.shadowtorcher.soulknife.exception.BeanConfigErrorException;
import com.shadowtorcher.stdisk.bean.PermissionBean;
import com.shadowtorcher.stdisk.bean.UserBean;
import com.shadowtorcher.stdisk.util.Permission;
import com.shadowtorcher.stdisk.util.StaticUtils;

import java.sql.SQLException;
import java.util.List;

public class Register {
    public void insertUser(String username, String password, String permission) {
        UserBean userBean = new UserBean();
        userBean.setUserName(username);
        userBean.setPassword(StaticUtils.getMd5(password));
        userBean.setUsedSpace(0);
        userBean.setUserID(StaticUtils.generatorStringUUID());
        try {
            List<PermissionBean> permissions = SoulKnifeDB.selectAll().setClass(PermissionBean.class);
            permissions.sort((p1, p2) -> {
                int i = Integer.parseInt(new Permission(p1).get("size"));
                int k = Integer.parseInt(new Permission(p2).get("size"));
                return i - k;
            });
            switch (permission) {
                case "普通用户":
                    userBean.setPermissionID(permissions.get(0).getPermissionID());
                    break;
                case "高级用户":
                    userBean.setPermissionID(permissions.get(permissions.size() - 1).getPermissionID());
                    break;
                default:
                    userBean.setPermissionID(permissions.get(0).getPermissionID());
            }
            userBean.save();
        } catch (BeanConfigErrorException | SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
